package org.hbkj.springbootmybatis.controller;

import io.swagger.v3.oas.annotations.Operation;
import org.hbkj.springbootmybatis.entity.GoodsDo;
import org.hbkj.springbootmybatis.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @GetMapping("/{id}")
    @Operation(summary = "获取商品信息", description = "使用id获取商品信息")
    public GoodsDo getOne(@PathVariable("id") long id) {
        return goodsService.getById(id);
    }

    @GetMapping
    @Operation(summary = "查询商品列表", description = "获取所有商品信息")
    public List<GoodsDo> getList() {
        return goodsService.getAll();
    }

    @PostMapping
    @Operation(summary = "新增商品", description = "添加新商品")
    public void add(@RequestBody GoodsDo goods) {
        goodsService.add(goods);
    }

    @PutMapping("/{id}")
    @Operation(summary = "修改商品", description = "更新商品信息")
    public void update(@PathVariable("id") long id, @RequestBody GoodsDo goods) {
        goods.setId(id);
        goodsService.edit(goods);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除商品", description = "根据ID删除商品")
    public void delete(@PathVariable("id") long id) {
        goodsService.remove(id);
    }

    @GetMapping("/available")
    @Operation(summary = "查询有库存的商品", description = "获取剩余量大于0的商品列表")
    public List<GoodsDo> getAvailableGoods() {
        return goodsService.getByRemaining(0); // 剩余量大于 0，所以传 0
    }

    @PostMapping("/{id}/purchase")
    @Operation(summary = "购买商品", description = "扣减商品库存，完成购买流程")
    public String purchaseGoods(
            @PathVariable("id") Long id,
            @RequestParam("purchaseCount") Integer purchaseCount) {
        boolean success = goodsService.deductStock(id, purchaseCount);
        return success ? "购买成功" : "库存不足";
    }
}